package com.laxcen.basiclib.core.task.core.thread;


import android.text.TextUtils;

import java.util.Set;
import java.util.concurrent.ExecutorService;

/**
 *  线程池管理
 */
public class ThreadPoolManager {

    private static volatile boolean sInit = false;
    private static ThreadPoolConfig sConfig;

    public static void init(ThreadPoolConfig config) {
        if (sInit) {
            return;
        }
        sInit = true;
        sConfig = config;
    }

    /**
     * 如果groupName不存在会返回一个默认的线程池
     * @param groupName
     * @return
     */
    public static final ExecutorService getExecutorService(String groupName) {
        return getService(groupName).getExecutorService();
    }

    private static IExecutorService getService(String groupName) {
        checkInit();
        IExecutorService service = sConfig.getService(groupName);
        if (service == null) {
            throw new IllegalArgumentException("groupName:" + groupName + " no register");
        }
        return service;
    }


    /**
     *
     * @param groupName 线程池组名称
     * @param command 任务队列
     * @param tag 任务tag 可以根据这个tag 批量删除跟tag相关的任务
     * @param delayTime 延时使时间
     */
    public static void execute(String groupName, Runnable command, String tag, int delayTime, int priority) {
        getService(groupName).execute(command, tag, delayTime, priority);
    }

    /**
     * 通过tag移除所有线程池组消息
     * @param tag
     */
    public static void removeAllByTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        Set<String> groupNames = sConfig.getGroupNames();
        for (String groupName : groupNames) {
            getService(groupName).removeAllByTag(tag);
        }
    }

    /**
     * 移除指定线程池组中的指定的tag
     * @param groupName
     * @param tag
     */
    public static void removeMessages(String groupName, String tag) {
        if (TextUtils.isEmpty(groupName) || TextUtils.isEmpty(tag)) {
            return;
        }
        getService(groupName).removeAllByTag(tag);
    }

    /**
     * 移除指定线程池组中的所有的消息
     * @param groupName
     */
    public static void removeCallbacksAndMessages(String groupName) {
        if (TextUtils.isEmpty(groupName)) {
            return;
        }
        getService(groupName).removeCallbacksAndMessages();
    }


    private static void checkInit() {
        if (!sInit) {
            throw new IllegalArgumentException("thread pool no inti");
        }
    }
}

